<?php #Функции магазина.

function ruWrap( $sentence )
{
    if ( !$sentence )
        return false;

    $new_sentence = $rus_char = '';
    $count_chars  = mb_strlen( $sentence );

    for ( $i = 0; $i < $count_chars; $i++ )
    {
        $char = mb_substr( $sentence, $i, 1 );

        if ( preg_match( '#[а-я]+#isU', $char ) )
        {
            $rus_char .= $char;
            continue;
        }
        else
        {
            if ( $rus_char )
            {
                $char     = '<span class="red_product_name">' . $rus_char . '</span>' . $char;
                $rus_char = '';
            }
        }
        $new_sentence .= $char;
    }
    if ( $rus_char )
        $new_sentence .= '<span class="red_product_name">' . $rus_char . '</span>';

    return $new_sentence;
}

function deleteOldFiles( $path, $age = 30 )
{
    global $elog;
    $dir = opendir( $path );
    while ( $file_name = readdir( $dir ) )
    {
        if ( $file_name == '.' || $file_name == '..' || is_dir( $path . '/' . $file_name ) )
            continue;

        $file = $path . '/' . $file_name;
        $days = getNumberDaysFromCreationFile( $file );
        if ( $days > $age )
        {
            unlink( $file );
            $elog->add( 'Удален старый файл: ' . $file_name );
        }
    }
}

function getNumberDaysFromCreationFile( $file )
{
    $days = 0;
    if ( is_file( $file ) )
    {
        $now_time  = time();
        $file_time = filemtime( $file );
        $days      = intval( ( $now_time - $file_time ) / 24 / 60 / 60 );
    }
    return $days;
}

function ToFuckThisChar( $sentence )
{ // Избавляемся от символа перевода строки
    $str   = '';
    $words = str_split( $sentence );
    foreach ( $words as $word )
    {
        if ( $word == ' ' )
        {
            $str .= $word;
        }
        else
        {
            if ( $word == trim( $word ) )
            {
                $str .= $word;
            }
        }
    }
    return $str;
}

function getParserSessionId( $session ) // Функция добавляет в базу новую сессию
{
    global $conn;
    static $store = array();

    if ( isset( $store[ $session ] ) )
        return $store[ $session ];

    $id                = $conn->query( 'INSERT INTO `parser_sessions` SET `session` = ' . $session . '
							ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID( id ), `session` = ' . $session, true );
    $store[ $session ] = $id;
    return $id;
}

function getParserCategoryId( $name ) // Функция добавляет в базу новый бренд и возвращает ID добавленного бренда
{
    global $conn;
    static $store = array();

    if ( isset( $store[ $name ] ) )
        return $store[ $name ];

    $id             = $conn->query( 'INSERT INTO `parser_categories` SET `name` = "' . mysql_real_escape_string( $name ) . '"
							ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID( id ), `name` = "' . mysql_real_escape_string( $name ) . '"', true );
    $store[ $name ] = $id;
    return $id;
}

function updateAll( $codes )
{
    updateIndexesTableProducts( $codes ); // Обновление кеша
    $errors = updateXmlFiles(); // Обновление XML
    $date   = date( "Y-m-d-H-i-s" );
    createXmlArchives( $date ); // Архивация XML
    createCsvArchives( $date ); // Архивация CSV
    deleteOldFiles( PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_XML_DIR, 30 ); // Удаление архивных Xml прайсов старше 1 месяца
    deleteOldFiles( PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_CSV_DIR, 30 ); // Удаление архивных Csv файлов старше 1 месяца
    deleteOldFiles( PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_EXPORT_FILES_DIR, 5 ); // Удаление эспортных Csv файлов старше 1 дня
    return $errors;
}

function getBrandId( $name ) // Функция добавляет в базу новый бренд и возвращает ID добавленного бренда
{
    global $conn;
    static $store = array();

    if ( isset( $store[ $name ] ) )
        return $store[ $name ];

    $name = mysql_real_escape_string( $name );
    $url  = getGoodUrl( $name );

    $id             = $conn->query( 'INSERT INTO `store_product_brand` SET `name` = "' . $name . '", `url` = "' . $url . '"
									ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID( id ), `name` = "' . $name . '", `url` = "' . $url . '"', true );
    $store[ $name ] = $id;
    return $id;
}

function updateIndexesTableProducts( $codes = array() )
{
	global $conn, $elog;
	$s = time();

	$all = !count( $codes ) ? true : false;

	if ( $all )
	{
		$conn->query( 'TRUNCATE TABLE store_products_cache' );
		$conn->query( 'ALTER TABLE store_products_cache DISABLE KEYS' );
		$conn->query( 'SELECT * FROM `store_products_view`', 0, 1 );
	}
	else
	{
		$conn->query( 'DELETE FROM `store_products_cache` WHERE `product_code` IN( ' . implode( ', ', $codes ) . ' )' );
		$conn->query( 'SELECT * FROM `store_products_view` WHERE `product_code` IN( ' . implode( ', ', $codes ) . ' )', 0, 1 );
	}
	while ( $row = $conn->fetch( 1 ) )
	{
		$conn->query( 'INSERT INTO `store_products_cache` SET
								`product_code`		= ' . $row->product_code . ',
								`product_id`		= ' . $row->product_id . ',
								`page_id`			= ' . $row->page_id . ',
								`parents`			= "' . $row->parents . '",
								`prefix`			= "' . mysql_real_escape_string( $row->prefix ) . '",
								`brand`				= "' . mysql_real_escape_string( $row->brand ) . '",
								`name`				= "' . mysql_real_escape_string( $row->name ) . '",
								`market_name`		= "' . mysql_real_escape_string( $row->market_name ) . '",
								`index_full_name`	= "' . getGoodUrl( $row->prefix . ' ' . $row->brand . ' ' . $row->name, '' ) . '",
								`url`				= "' . getProductBeforeUrl( $row->parents ) . $row->url . '",
								`price_retail`		= ' . $row->price_retail . ',
								`brand_id`			= ' . ( $row->brand_id ? $row->brand_id : 0 ) . ',
								`pp`				= ' . ( strlen( $row->pp ) ? $row->pp : 'NULL' ) . ',
								`pp2`				= ' . ( strlen( $row->pp2 ) ? $row->pp2 : 'NULL' ) . ',
								`pd`				= ' . ( strlen( $row->pd ) ? $row->pd : 'NULL' ) . ',
								`pm`				= ' . ( strlen( $row->pm ) ? $row->pm : 'NULL' ) . ',
								`bid`				= ' . ( strlen( $row->bid ) ? '"' . $row->bid . '"' : 'NULL' ) . ',
								`cbid`				= ' . ( strlen( $row->cbid ) ? '"' . $row->cbid . '"' : 'NULL' ) . ',
								`volume`			= ' . ( strlen( $row->volume ) ? $row->volume : 'NULL' ) . ',
								`new`				= ' . ( strlen( $row->new ) ? $row->new : 'NULL' ) . ',
								`hit`				= ' . ( strlen( $row->hit ) ? $row->hit : 'NULL' ) . ',
								`sale`				= ' . ( strlen( $row->sale ) ? $row->sale : 'NULL' ) . ',
								`accessories`		= ' . ( strlen( $row->accessories ) ? '"' . $row->accessories . '"' : 'NULL' ) . ',
								`similar`			= ' . ( strlen( $row->similar ) ? '"' . $row->similar . '"' : 'NULL' ) . ',
								`price_inst`		= ' . ( strlen( $row->price_inst ) ? '"' . (int) $row->price_inst . '"' : 'NULL' ) . ',
								`price_vip`			= ' . ( strlen( $row->price_vip ) ? '"' . (int) $row->price_vip . '"' : 'NULL' ) . ',
								`category_id`		= ' . $row->category_id . ',
								`country_of_origin`	= "'. $row->country_of_origin .'",
								`manufacturer_warranty`	= "'. $row->manufacturer_warranty .'"'
		);
	}

	if ( $all )
		$conn->query( 'ALTER TABLE store_products_cache ENABLE KEYS' );

	$elog->add( 'Кеш сбросился (' . ( time() - $s ) . ' сек)' );
}

function startUpdateServices( $fine_name, $fields )
{
    $s = time();
    require( 'func.update_price.php' ); // Обновляем прайс
    $db_obj = new UpdatePrice();
    $info   = $db_obj->startUpdate( $fine_name, $fields );
    $GLOBALS[ 'elog' ]->add( 'Служебки обновлены (' . ( time() - $s ) . ' сек)' );
    return $info;
}

function startImportProduct( $fine_name )
{
    $s = time();
    require( 'func.import_product.php' );
    $db_obj      = new Import();
    $info_import = $db_obj->startImport( $fine_name );
    $GLOBALS[ 'elog' ]->add( 'Товары импортированы (' . ( time() - $s ) . ' сек)' );
    return $info_import;
}

function avtoUpdatePrice() // Обновление XML каждые пол часа
{
    global $conn;
    $current_time      = time();
    $half_hour_seconds = 3600;
    $conn->query( 'SELECT * FROM xml_price_update_times ORDER BY id DESC LIMIT 1' );
    if ( $row = $conn->fetch() )
    {
        if ( $current_time > ( $row->update_time + $half_hour_seconds ) )
        {
            $conn->query( 'INSERT INTO `xml_price_update_times` ( `update_time` ) VALUES ( ' . $current_time . ' )' );

            $pm   = 1;
            $cbid = 30;

            if ( $row->id % 2 )
                $pm = $cbid = 0;

            $conn->query( 'UPDATE `store_products`		SET pm = ELT(FIELD( `product_code`, 40782, 25978, 52699, 46439 ), 1, 1, ' . $pm . ', ' . $pm . ' ) WHERE `product_code` IN ( 40782, 25978, 52699, 46439 )' );
            $conn->query( 'UPDATE `store_products_cache`	SET pm = ELT(FIELD( `product_code`, 40782, 25978, 52699, 46439 ), 1, 1, ' . $pm . ', ' . $pm . ' ) WHERE `product_code` IN ( 40782, 25978, 52699, 46439 )' );

            $conn->query( 'UPDATE `store_products`		SET cbid = ELT(FIELD( `product_code`, 40782, 25978, 52699, 46439 ), ' . $cbid . ', ' . $cbid . ', ' . $cbid . ', ' . $cbid . ' ) WHERE `product_code` IN ( 40782, 25978, 52699, 46439 )' );
            $conn->query( 'UPDATE `store_products_cache`	SET cbid = ELT(FIELD( `product_code`, 40782, 25978, 52699, 46439 ), ' . $cbid . ', ' . $cbid . ', ' . $cbid . ', ' . $cbid . ' ) WHERE `product_code` IN ( 40782, 25978, 52699, 46439 )' );

            $date   = date( "Y-m-d-H-i-s" );
            $errors = updateXmlFiles( true ); // Обновление XML
            createXmlArchives( $date ); // Архивация XML
            createCsvArchives( $date ); // Архивация CSV
        }
    }
    else
    {
        $conn->query( 'INSERT INTO `xml_price_update_times` ( `update_time` ) VALUES ( ' . $current_time . ' )' );
    }
}

function updateXmlFiles( $avtomatical = false )
{
    global $elog, $xml, $conn;
    $s = time();

    require_once( 'func.export_xml.php' );
//	error_reporting(E_ALL);
    $xml    = new xml_generate( $conn );
    $errors = $xml->getingXml( $avtomatical );
    $elog->add( 'XML обновлен (' . ( time() - $s ) . ' сек)' );

    return $errors;
}

function createXmlArchives( $date ) // Архивнуть основной прайс
{
    startArchive( PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_XML_DIR . '/ym_price_' . $date . '.zip', PATH_TO_INC_DIR . '/ym_price.xml', 'ym_price_' . $date . '.xml' );
    $GLOBALS[ 'elog' ]->add( 'XML архивнулся' );
}

function createCsvArchives( $date ) // Архивнуть CSV со служебками
{
    $file_name = getExportProducts( $date, $with_service = true );
    startArchive( PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_CSV_DIR . '/export_' . $date . '.zip', PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_EXPORT_FILES_DIR . '/' . $file_name, $file_name );
    $GLOBALS[ 'elog' ]->add( 'CSV архивнулся' );
}

function getExportProducts( $date = '', $with_service = false )
{
    global $elog;
    $s    = time();
    $date = $date ? $date : date( "Y-m-d-H-i-s" );
    require( 'func.export_products.php' ); // Обновляем прайс
    $db_obj    = new Export_Product();
    $file_name = $db_obj->startExport( $date, $with_service );
    $elog->add( 'Товары экспортнулись (' . ( time() - $s ) . ' сек)' );
    return $file_name;
}

function getProductBeforeUrl( $parents )
{
    $url_before = '';
    static $store_ids = array();

    if ( count( $store_ids ) == 0 )
    {
        global $conn;
        $conn->query( 'SELECT `id`, `url` FROM `pages` WHERE `templ` IN( "category", "sub_category" )', false, 'getProductBeforeUrl' );
        while ( $row = $conn->fetch( 'getProductBeforeUrl' ) )
            $store_ids[ $row->id ] = $row->url;
    }

    $ids = getIdsArr( $parents );
    foreach ( $ids as $id )
        $url_before .= $store_ids[ $id ] . '/';

    return $url_before;
}


function getBasketId()
{
    avtoUpdatePrice();
    // register_shutdown_function('avtoUpdatePrice');  //  функция срабатывает после
    return isset( $_COOKIE[ 'basket_id' ] ) ? $_COOKIE[ 'basket_id' ] : 0;
}

function setBasketId()
{
    static $basket_id;

    if ( $basket_id )
        return $basket_id;

    global $conn;
    if ( isset( $_COOKIE[ 'basket_id' ] ) )
    {
        $conn->query( 'SELECT `id` FROM `store_baskets` WHERE `id` = ' . $_COOKIE[ 'basket_id' ] . ' AND `status` = "basket"' );
        $basket_id = ( $row = $conn->fetch() ) ? $row->id : 0;
    }

    if ( !$basket_id )
        $basket_id = $conn->query("INSERT INTO `store_baskets` ( `user_id` , `date_order` )
		                VALUES ('{$GLOBALS[ 'user' ]->id}', now())", true );

    setBasketCookieIfNotExist( $basket_id );
    return $basket_id;
}

function setBasketCookieIfNotExist( $basket_id )
{
    if ( empty( $_COOKIE[ 'basket_id' ] ) )
        setcookie( 'basket_id', $basket_id, 9999999999, '/' );
    elseif ( $_COOKIE[ 'basket_id' ] != $basket_id )
        setcookie( 'basket_id', $basket_id, 9999999999, '/' );
}

function getCountProduct( $basket_id, $pr_code = 0 )
{
    $count = array( 'products' => 0, 'product' => 0, 'inst' => 0, 'vip' => 0 );
    if ( $basket_id )
    {
        global $conn;
        $conn->query( 'SELECT sum(`count`) AS `count_product` FROM `store_basket_products` WHERE `basket_id` = ' . $basket_id );
        if ( $row = $conn->fetch() )
            $count[ 'products' ] = $row->count_product ? $row->count_product : 0;

        if ( $pr_code )
        {
            $conn->query( 'SELECT `count`, `count_inst`, `count_vip` FROM `store_basket_products` WHERE `basket_id` = ' . $basket_id . ' AND `product_code` = ' . $pr_code );
            if ( $row = $conn->fetch() )
            {
                $count[ 'product' ] = $row->count;
                $count[ 'inst' ]    = $row->count_inst;
                $count[ 'vip' ]     = $row->count_vip;
            }
        }
    }
    return $count;
}

function cropStr( $str, $count = 10 )
{
    $strs = explode( ' ', $str, $count );
    array_pop( $strs );
    return implode( ' ', $strs );
}

function checkPhone( $phone )
{
    $patt = '/^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/';
    return preg_match( $patt, $phone ) ? true : false;
}

function prepareErrors( $errors )
{
    $error_mess = '';
    foreach ( $errors as $error )
        $error_mess .= '<li>' . $error . '</li>';

    $error_mess  = ( !isset( $errors[ 'email_exist' ] ) ) ? $error_mess : $errors[ 'email_exist' ];
    $errors_mess = '<strong>Обнаружены следующие ошибки:</strong> <ul>' . $error_mess . '</ul>';
    return $errors_mess;
}

function setFilterData( $data = false )
{
    static $filter;
    if ( !$data ) return $filter;
    $filter = $data;
}

function getImageSrcNew( $product_code, $size )
{
    if ( !file_exists( HOME_PATH . '/inc/images/products/' . $product_code . '.jpg' ) )
        $path_to_pic = '/inc/images/bg/no_image.jpg';
    else
        $path_to_pic = '/inc/images/products/' . $product_code . '.jpg';

    $img = $GLOBALS[ 'load' ]->module( 'imager', 'getThumbName', array( 'original_name' => $path_to_pic, 'size' => $size ) );
    return $img;
}

function getExportFile( $file_name ) // Выдать файл на скачку
{
    $path = PATH_TO_FILES . '/' . PATH_TO_ARCHIVE_EXPORT_FILES_DIR . '/' . $file_name;
    if ( file_exists( $path ) )
    {
        header( "Content-Type: text/html; charset=UTF-8" );
        header( "Content-Type: application/octet-stream" );
        header( "Accept-Ranges: bytes" );
        header( "Content-Length: " . filesize( $path ) );
        header( "Content-Disposition: attachment; filename=" . $file_name );
        ob_clean();
        flush();
        readfile( $path );
    }
    else
    {
        echo 'Файл не существует';
    }
}

function send_email_my( $subject, $message, $mail_to = '' )
{
    global $load;

    if( $mail_to != '' ){
        $load->module( 'email', 'send', array( 'mail_to' => $mail_to, 'subject' => $subject, 'message' => $message ) );
    } else {
        if ( defined( 'MAIL_TO_ADRESS' ) )
            $load->module( 'email', 'send', array( 'mail_to' => MAIL_TO_ADRESS, 'subject' => $subject, 'message' => $message ) );
        if ( defined( 'MAIL_TO_ADRESS_COPY' ) )
            $load->module( 'email', 'send', array( 'mail_to' => MAIL_TO_ADRESS_COPY, 'subject' => $subject, 'message' => $message ) );
        if ( defined( 'MAIL_TO_ADRESS_MY' ) )
            $load->module( 'email', 'send', array( 'mail_to' => MAIL_TO_ADRESS_MY, 'subject' => $subject, 'message' => $message ) );
    }
}

function addNewUser( $name, $email = '', $pass = '' )
{
    global $conn;
    return $conn->query( '	INSERT INTO `users` SET `name`				= "' . mysql_escape_string( $name ) . '",
											`email`				= "' . ( $email ? mysql_escape_string( $email ) : 'no' ) . '",
											`password`			= "' . ( $pass ? md5( $pass ) : 'no' ) . '",
											`date_registred`	= now(),
											`group_id`			= ( SELECT `id` FROM `groups` WHERE `type` = "users" AND `name_sys` = "buyer" )
										', true );
}

function getUserData( $user_id )
{
    GLOBAL $conn;
    $users_datas = array();
    $conn->query( "SELECT * FROM `users_datas` WHERE `user_id` = $user_id" );
    if ( $conn->rowCount() > 0 )
    {
        while ( $row = $conn->fetch() )
        {
            $users_datas[ $row->prop_name ][ $row->id ] = $row->value;
        }
    }
    return $users_datas;
}

function addNewPhone( $user_id, $phone )
{
    global $conn;
    $phone = mysql_escape_string( $phone );
    return $conn->query( 'INSERT INTO `users_datas` ( `user_id` , `prop_name`, `value` ) VALUES ( ' . $user_id . ' , "phone" , "' . $phone . '" ) ', true );
}

function myIconv( $str, $set = 'uw' ) // Меняет кодировку
{
    return ( $set == 'uw' ) ? iconv( "UTF-8", "WINDOWS-1251", $str ) : iconv( "WINDOWS-1251", "UTF-8", $str );
}

function iconvWU( $str ) // Меняет кодировку
{
    return iconv( "WINDOWS-1251", "UTF-8", $str );
}

function iconvUW( $str ) // Меняет кодировку
{
    return iconv( "WINDOWS-1251", "UTF-8", $str );
}

function getPriceFormat( $price, $double_digits = 0 )
{
    $price = str_replace( array( ',', ' ' ), array( '.', '' ), $price );
    if ( empty( $price ) )
        $price = 0;
    return number_format( $price, $double_digits, ',', ' ' );
}

//Функция для товаров новогодней акции
function getNewYearProducts( $product_code )
{
    GLOBAL $conn, $view;
    $ny_products = array();

    if ( is_array( $product_code ) )
    {
        $product_codes = implode( ", ", $product_code );

        $conn->query( "SELECT product_code, bonus FROM ny_promo_products WHERE product_code in({$product_codes})", false, 'get_credits' );

        if ( $conn->rowCount( 'get_credits' ) )
        {
            while ( $row = $conn->fetch( 'get_credits' ) )
            {
                $ny_products[ $row->product_code ] = $row->bonus;
            }
        }
        return $ny_products;
    }
    else
    {
        $conn->query( "SELECT product_code, bonus FROM ny_promo_products where product_code = {$product_code}" );

        if ( $conn->rowCount() )
        {
            $row                               = $conn->fetch();
            $ny_products[ $row->product_code ] = $row->bonus;

            return $ny_products[ $row->product_code ];
        }
        else
            return '';
    }
}

function getProductPresent( $product_code )
{
    GLOBAL $conn, $view;
    $present_info = array();

    if ( is_array( $product_code ) )
    {
        $product_codes = implode( ", ", $product_code );

        $conn->query(
            "SELECT pr.product_code as product_code, prefix, brand, name, url FROM `product_presents` pr
				JOIN store_products_cache cache ON pr.present = cache.product_code
					WHERE pr.product_code in ({$product_codes})", false, 'get_present'
        );

        if ( $conn->rowCount( 'get_present' ) )
        {
            while ( $row = $conn->fetch( 'get_present' ) )
            {
                $present_info[ $row->product_code ][ 'name' ] = mb_strtolower( $row->prefix ) . ' ' . strtolower( $row->brand ) . ' ' . $row->name;
                $present_info[ $row->product_code ][ 'url' ]  = $row->url;
            }
        }

    }
    else
    {
        $conn->query( "SELECT prefix, brand, name, url FROM `product_presents` pres
								JOIN store_products_cache cache ON pres.present = cache.product_code
									WHERE pres.product_code = {$product_code}", false, 'get_present' );

        if ( $conn->rowCount( 'get_present' ) )
        {
            $get_present  = $conn->fetch( 'get_present' );
            $present_name = mb_strtolower( $get_present->prefix ) . ' ' . strtolower( $get_present->brand ) . ' ' . $get_present->name;
            $present_url  = $get_present->url;
        }
        else
        {
            $present_name = $present_url = '';
        }

        $present_info[ 'name' ] = $present_name;
        $present_info[ 'url' ]  = $present_url;
    }
    return ( $present_info );
}

function getProductById( $product_code = 0 )
{
    GLOBAL $conn, $view;
    static $cache = array();
    $clause = $product_code ? '`product_code` = ' . $product_code : '`page_id` = ' . $view->id;

    if ( isset( $cache[ $clause ] ) )
        return $cache[ $clause ];

    $conn->query( 'SELECT * FROM `store_products_view` WHERE ' . $clause );
    if ( $row = $conn->fetch() )
    {
        $cache[ $clause ] = $row;

        $present_info = getProductPresent( $row->product_code );

        foreach ( $present_info as $name => $val )
        {
            if ( $name == 'name' )
            {
                $row->present_name = $present_info[ 'name' ];
                continue;
            }
            if ( $name == 'url' )
            {
                $row->present_url = $present_info[ 'url' ];
            }
        }
        $row->ny_product_bonus = getNewYearProducts( $row->product_code );
        return $row;
    }
    return false;
}

function getBasketList( $basket_id )
{
    $params = array( 'where' => '`basket_id` = ' . $basket_id );
    return $basket_id ? getProductList( $params, 'store_basket_view' ) : array( 'list' => array() );
}

function getProductList( $params, $table = 'store_products_cache' )
{
    global $conn;
    $users  = isset( $GLOBALS[ 'users' ] ) ? $GLOBALS[ 'users' ] : array();
    $admin  = in_array( $GLOBALS[ 'user' ]->id, $users ) ? true : false;
    $clause = array();

    $products = array( 'list' => array(), 'count' => 0, 'fact_count' => 0 );

    if ( isset( $params[ 'where' ] ) )
        $clause[ ] = $params[ 'where' ];
    if ( !$admin )
        $clause[ ] = '`price_retail` > 0 AND `pp` IS NOT NULL';
    $where = count( $clause ) ? 'WHERE ' . implode( ' AND ', $clause ) : '';

    $order     = isset( $params[ 'order' ] ) ? $params[ 'order' ] : '';
    $limit     = isset( $params[ 'limit' ] ) ? $params[ 'limit' ] : '';
    $limit_num = isset( $params[ 'limit_num' ] ) ? $params[ 'limit_num' ] : '';

    $calc      = ( $limit || $limit === 0 ) ? 'sql_calc_found_rows' : '';
    $order     = $order ? 'ORDER BY ' . $order : '';
    $limit_num = $limit_num ? $limit_num . ', ' : '';
    $limit     = ( $limit || $limit === 0 ) ? 'LIMIT ' . $limit_num . ' ' . $limit : '';

    $query = 'SELECT ' . $calc . ' * FROM `' . $table . '` ' . $where . ' ' . $order . ' ' . $limit;
    $conn->query( $query, false, 'product_list' );



    if ( $calc ) // Получаем количество товаров
    {
        $conn->query( 'SELECT found_rows() AS `num`' );
        $total               = $conn->fetch();
        $products[ 'count' ] = $total ? $total->num : 0;
    }
    else
    {
        $products[ 'count' ] = $conn->rowCount( 'product_list' );
    }
    $products_code = array();
    while ( $product = $conn->fetch( 'product_list' ) )
    {
        if ( $table != 'store_products_cache' )
            $product->url = getProductBeforeUrl( $product->parents ) . $product->url;

        $products[ 'list' ][ ] = $product;
        $products_code[ ]      = $product->product_code;
        $products[ 'fact_count' ]++;
    }
    $products[ 'presents' ] = getProductPresent( $products_code );
    $products[ 'credits' ]  = getNewYearProducts( $products_code );

    return $products;
}

function getBasketProducts( $basket_id, $need_host = false, $delivery_type = 'courier' )
{
    $basket_products = getBasketList( $basket_id );
    if ( count( $basket_products[ 'list' ] ) == 0 )
        return '';

    $host_name                = $need_host ? HOST_NAME : '';
    $products                 = array();
    $products[ 'total' ]      = $products[ 'product_count' ] = 0;
    $volumes                  = array();
    $costs                    = getTotalCosts( $basket_id, $delivery_type );
    $products[ 'total_cost' ] = (int) $costs[ 'total' ];

    $list = '<table cellpadding="5" border="1" style="border-collapse: collapse;">
					<tr>
						<td><b>Наименование</b></td>
						<td><b>Цена, руб.</b></td>
						<td><b>Кол-во, шт.</b></td>
						<td><b>Стоимость, руб.</b></td>
					</tr>';

	$products_vip = $products_inst = $products_inst_all = $products_vip_all = array();

    foreach ( $basket_products[ 'list' ] as $product )
    {
        //GAitems
        $products[ 'products_for_metrika' ][ ] = array(
            'order_id' => $product->basket_id,
            'code'     => $product->product_code,
            'name'     => $product->name,
            'category' => $product->prefix . ' ' . $product->brand,
            'price'    => getPriceFormat( $product->price_retail ),
            'quantity' => $product->count
        );

        $product_coast = str_replace( ' ', '', $product->price_retail );
        $cost          = $product_coast * $product->count;
        $products[ 'total' ] += $cost;
        $products[ 'product_count' ] += $product->count;
        $delivery_cost = isset( $costs[ $delivery_type ] ) ? $costs[ $delivery_type ] : $costs[ 'courier' ];

        $present_info = getProductPresent( $product->product_code );

        if ( $present_info[ 'name' ] != '' && $present_info[ 'url' ] != '' )
        {
            $order_present_html = '
					<p style="color: #4d7408">К товару прилагается подарок: 
						<a style="color: #4d7408; font-size: 12px;" href="' . $host_name . '/' . $present_info[ 'url' ] . '">' . $present_info[ 'name' ] . '</a>
					<p>';
        }
        else
            $order_present_html = '';

        $list .= '	<tr>
						<td>
							<a href="' . $host_name . '/' . $product->url . '">' . $product->prefix . ' ' . $product->brand . ' <strong>' . $product->name . '</strong></a> <small>(' . $product->product_code . ')</small>' . $order_present_html . '
						</td>
						<td style="text-align: right">' . getPriceFormat( $product->price_retail ) . '</td>
						<td style="text-align: center">' . $product->count . '</td>
						<td style="text-align: right">' . getPriceFormat( $product->price_retail * $product->count ) . '</td>
					</tr>';
        if ( $product->inst ) {
		   $list .= '	<tr>
						<td> - Монтаж</td>
						<td style="text-align: right">' . getPriceFormat( $product->price_inst ) . '</td>
						<td style="text-align: center">' . $product->count_inst . '</td>
						<td style="text-align: right">' . getPriceFormat( $product->price_inst * $product->count_inst ) . '</td>
					</tr>';
		   $products_inst[] = $product->price_inst;
	   }

        if ( $product->vip ) {
		   $list .= '	<tr>
						<td> - VIP сервис</td>
						<td style="text-align: right">' . getPriceFormat( $product->price_vip ) . '</td>
						<td style="text-align: center">' . $product->count_vip . '</td>
						<td style="text-align: right">' . getPriceFormat( $product->price_vip * $product->count_vip ) . '</td>
					</tr>';
		   $products_vip[] = $product->price_vip;
	   }

        $products[ 'order_list' ][ ] = $product;
        $products_code[ ]            = $product->product_code;

	    $products_inst_all[] = $product->price_inst;
	    $products_vip_all[] = $product->price_vip;
    }


    $products[ 'presents' ] = getProductPresent( $products_code );
    $products[ 'credits' ]  = getNewYearProducts( $products_code );

    $list .= '
					<tr>
						<td style="font-size: 14px;"><b>Стоимость ' . ( $delivery_type == 'courier' ? 'доставки' : 'самовывоза' ) . '</b></td>
						<td></td>
						<td></td>
						<td style="text-align: right;">' . getPriceFormat( $delivery_cost ) . '</td>
					</tr>
					<tr>
						<td style="font-size: 14px;"><b>Итоговая стоимость</b></td>
						<td></td>
						<td></td>
						<td style="text-align: right">' . getPriceFormat( $costs[ 'total' ] ) . '</td>
					</tr>
				</table>';

		/*$products[ 'more_services' ] = '
				<h2>Дополнительные слуги:</h2>
				<table>
					'.( count($products_vip) == 0 ?
					'<tr>
						<td>ВИП-сервис</td>
						<td>'.getPriceFormat( array_sum($products_vip_all) ).'</td>
					</tr>' : '' ).
					( count($products_inst) == 0 ?
					'<tr>
						<td>Монтаж</td>
						<td>'.getPriceFormat( array_sum($products_inst_all) ).'</td>
					</tr>' : '' ).'
					<tr>
						<td>Утилизация</td>
						<td>400</td>
					</tr>
					<tr>
						<td>Демонтаж</td>
						<td>400</td>
					</tr>
				</table>';*/


	/*if(count($products_vip) == 0)
		echo array_sum($products_vip_all).' ';
	if(count($products_inst) == 0)
		echo array_sum($products_inst_all);

	print_r($products_vip);

	echo '<br/>'.count($products_vip).' '.count($products_inst).'<br/>';*/

    $products[ 'list' ] = ( $products[ 'product_count' ] > 0 ) ? $list : '';
    return $products;
}




function calculateCostDelivery( $basket_id, $delivery_type ) // Получить стоимость доставки
{
    global $conn;
    global $COST_OF_DELIVERY_1;
    global $COST_OF_DELIVERY_2;
    global $SELF_DELIVERY;

    $costs = $volumes = array();
    $total = 0;

    $conn->query( 'SELECT `count`, `volume` FROM `store_basket_view` WHERE `basket_id` = ' . $basket_id );
    while ( $row = $conn->fetch() )
    {
        if ( $row->volume ) // Если для товара имеется доставка
            for ( $i = 1; $i <= $row->count; $i++ ) // Учитывает количество повторяющихся товаров
            {
                if ( isset( $COST_OF_DELIVERY_1[ $row->volume ] ) && isset( $COST_OF_DELIVERY_2[ $row->volume ] ) && isset( $SELF_DELIVERY[ $row->volume ] ) )
                    $volumes[ ] = $row->volume;
            }

    }

    if ( count( $volumes ) )
    {
        if ( $delivery_type == 'courier' )
        {
            foreach ( $volumes as $vol )
                $costs[ ] = $COST_OF_DELIVERY_1[ $vol ];

            arsort( $costs );

            $i = 1;
            foreach ( $costs as $key => $cost )
            {
                if ( $i++ == 1 )
                    unset( $volumes[ $key ] );
            }

            $total = array_shift( $costs );

            foreach ( $volumes as $vol )
                $total += $COST_OF_DELIVERY_2[ $vol ];
        }
        else
        {
            foreach ( $volumes as $vol )
                $total += $SELF_DELIVERY[ $vol ];
        }
    }
    return $total;
}

function getTotalCosts( $basket_id, $delivery_type = 'courier', $pr_code = 0 )
{
    $costs = array( 'total' => 0, 'courier' => 0, 'self' => 0, 'product' => 0, 'inst' => 0, 'vip' => 0 );

    if ( $basket_id )
    {
        global $conn;
        $conn->query( '	SELECT
								SUM(
									( `count` * `price_retail` ) + 
									IF( `inst` = 1, `count_inst` * IFNULL(`price_inst`, 0), 0 ) +
									IF( `vip` = 1, `count_vip` * IFNULL(`price_vip`, 0), 0 )
								) AS `total`
								FROM `store_basket_view`
								WHERE `basket_id` = ' . $basket_id );

        if ( $row = $conn->fetch() )
        {
            $costs[ 'courier' ] = calculateCostDelivery( $basket_id, 'courier' );
            $costs[ 'self' ]    = calculateCostDelivery( $basket_id, 'self' );
            $costs[ 'total' ]   = $row->total + $costs[ $delivery_type ];

            if ( $pr_code )
            {
                $conn->query( '	SELECT
											( `count` * `price_retail` ) AS price_product,
											( `count_inst` * IFNULL(`price_inst`, 0 ) ) AS `price_inst`,
											( `count_vip` * IFNULL(`price_vip`, 0 ) ) AS `price_vip`
										FROM `store_basket_view`
										WHERE `basket_id` = ' . $basket_id . ' AND `product_code` = ' . $pr_code );
                $row                = $conn->fetch();
                $costs[ 'product' ] = $row->price_product;
                $costs[ 'inst' ]    = $row->price_inst;
                $costs[ 'vip' ]     = $row->price_vip;
            }
        }
    }
    return $costs;
}

function displayMessage( $counts = 0, $costs = 0, $add_upd_product = array() )
{
    echo json_encode( array( 'counts' => $counts, 'costs' => $costs, 'add_upd_product' => $add_upd_product ) );
}

function disp_status( $message = '', $errors = '', $ya_params = '' )
{
    echo json_encode( array( 'message' => $message, 'errors' => $errors, 'ya_params' => $ya_params ) );
}

function del_cookie_basket_id()
{
    setcookie( 'basket_id' );
}